<template>
  <el-container class="layout-container">
    <el-aside :width="isCollapse ? '64px' : '200px'" class="aside">
      <div class="logo-container">
        <el-icon class="logo" :size="32"><Monitor /></el-icon>
        <span v-show="!isCollapse" class="title">XXXX后台管理平台</span>
      </div>
      <el-menu
        :router="true"
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
      >
        <el-menu-item index="/">
          <el-icon><HomeFilled /></el-icon>
          <template #title>首页</template>
        </el-menu-item>
        <el-menu-item index="/products">
          <el-icon><Goods /></el-icon>
          <template #title>商品管理</template>
        </el-menu-item>
        <el-menu-item index="/categories">
          <el-icon><Menu /></el-icon>
          <template #title>分类管理</template>
        </el-menu-item>
        <el-menu-item index="/users">
          <el-icon><User /></el-icon>
          <template #title>用户管理</template>
        </el-menu-item>
      </el-menu>
    </el-aside>
    
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-icon 
              class="collapse-btn"
              @click="toggleCollapse"
            >
              <Fold v-if="!isCollapse"/>
              <Expand v-else/>
            </el-icon>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item v-if="currentRoute.meta.title">
                {{ currentRoute.meta.title }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-dropdown>
            <span class="el-dropdown-link">
              管理员
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>个人信息</el-dropdown-item>
                <el-dropdown-item>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <div class="tags-view">
        <el-scrollbar class="tags-view-wrapper" ref="scrollbarRef">
          <div class="tags-view-container">
            <router-link
              v-for="(tag, index) in tagsStore.visitedViews"
              :key="tag.path"
              :to="tag.path"
              class="tags-view-item"
              :class="{ 
                active: isActive(tag),
                'first-tag': index === 0
              }"
              draggable="true"
              @dragstart="handleDragStart($event, index)"
              @dragover.prevent="handleDragOver($event, index)"
              @dragenter="handleDragEnter($event, index)"
              @dragleave="handleDragLeave"
              @drop="handleDrop($event, index)"
              @dragend="handleDragEnd"
              @contextmenu.prevent="openMenu($event, tag)"
            >
              <span>{{ tag.title }}</span>
              <el-icon 
                class="close-btn"
                v-if="tag.path !== '/'"
                @click.prevent.stop="closeTag(tag)"
              >
                <Close />
              </el-icon>
            </router-link>
          </div>
        </el-scrollbar>

        <!-- 右键菜单 -->
        <ul
          v-show="contextMenu.visible"
          :style="contextMenu.style"
          class="context-menu"
        >
          <li @click="refreshPage">
            <el-icon><Refresh /></el-icon>
            <span>刷新页面</span>
          </li>
          <li @click="closeOthersTags">
            <el-icon><CircleClose /></el-icon>
            <span>关闭其他</span>
          </li>
          <li @click="closeAllTags">
            <el-icon><Remove /></el-icon>
            <span>关闭所有</span>
          </li>
        </ul>
      </div>

      <el-main>
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  HomeFilled, 
  Goods, 
  User, 
  Menu, 
  Fold, 
  Expand, 
  Close,
  Refresh,
  CircleClose,
  Remove,
  Monitor,
  ArrowDown
} from '@element-plus/icons-vue'
import { useTagsStore, type TagView } from '@/stores/tags'

const route = useRoute()
const router = useRouter()
const tagsStore = useTagsStore()
const isCollapse = ref(false)

// 右键菜单相关
const contextMenu = reactive({
  visible: false,
  style: {
    left: '0px',
    top: '0px'
  },
  selectedTag: null as TagView | null
})

// 计算当前激活的菜单项
const activeMenu = computed(() => route.path)

// 计算当前路由信息
const currentRoute = computed(() => route)

// 判断标签是否激活
const isActive = (tag: any) => {
  return tag.path === route.path
}

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 监听路由变化，添加标签
router.beforeEach((to) => {
  if (to.meta?.title) {
    tagsStore.addView(to)
  }
  return true
})

// 关闭标签
const closeTag = (tag: TagView) => {
  const views = tagsStore.delView(tag)
  if (isActive(tag)) {
    const latestView = views.slice(-1)[0]
    router.push(latestView.path)
  }
}

// 右键菜单
const openMenu = (e: MouseEvent, tag: TagView) => {
  contextMenu.visible = true
  contextMenu.style.left = `${e.clientX}px`
  contextMenu.style.top = `${e.clientY}px`
  contextMenu.selectedTag = tag
}

const closeMenu = () => {
  contextMenu.visible = false
}

const refreshPage = () => {
  router.go(0)
  closeMenu()
}

const closeOthersTags = () => {
  if (contextMenu.selectedTag) {
    tagsStore.delOthersViews(contextMenu.selectedTag)
    router.push(contextMenu.selectedTag.path)
  }
  closeMenu()
}

const closeAllTags = () => {
  tagsStore.delAllViews()
  router.push('/')
  closeMenu()
}

// 点击其他地方关闭右键菜单
const handleClickOutside = (e: MouseEvent) => {
  const menu = document.querySelector('.context-menu')
  if (menu && !menu.contains(e.target as Node)) {
    closeMenu()
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})

const scrollbarRef = ref()
const draggedIndex = ref(-1)
const dragOverIndex = ref(-1)

// 拖拽相关方法
const handleDragStart = (e: DragEvent, index: number) => {
  if (index === 0) {
    e.preventDefault()
    return
  }
  draggedIndex.value = index
  if (e.dataTransfer) {
    e.dataTransfer.effectAllowed = 'move'
    // 设置拖动时的透明度
    const target = e.target as HTMLElement
    target.style.opacity = '0.4'
  }
}

const handleDragOver = (e: DragEvent, index: number) => {
  e.preventDefault()
  if (index === 0) return // 不允许拖到首页标签位置
  dragOverIndex.value = index
}

const handleDragEnter = (e: DragEvent, index: number) => {
  if (index === 0) return
  const target = e.target as HTMLElement
  if (target.classList.contains('tags-view-item')) {
    target.classList.add('drag-over')
  }
}

const handleDragLeave = (e: DragEvent) => {
  const target = e.target as HTMLElement
  if (target.classList.contains('tags-view-item')) {
    target.classList.remove('drag-over')
  }
}

const handleDrop = (e: DragEvent, index: number) => {
  e.preventDefault()
  if (index === 0 || draggedIndex.value === 0) return
  
  const target = e.target as HTMLElement
  target.classList.remove('drag-over')
  
  if (draggedIndex.value !== index) {
    tagsStore.sortTags(draggedIndex.value, index)
  }
}

const handleDragEnd = (e: DragEvent) => {
  const target = e.target as HTMLElement
  target.style.opacity = '1'
  draggedIndex.value = -1
  dragOverIndex.value = -1
}
</script>

<style scoped>
.layout-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.aside {
  background-color: #ffffff;
  transition: width 0.3s;
  overflow: hidden;
  border-right: 1px solid #e6e6e6;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  background: #ffffff;
  border-bottom: 1px solid #e6e6e6;
}

.logo {
  color: #409eff;
  font-size: 32px;
}

.title {
  color: #333333;
  margin-left: 12px;
  font-size: 18px;
  font-weight: 600;
}

.el-menu-vertical {
  border-right: none;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.collapse-btn {
  font-size: 20px;
  cursor: pointer;
  color: #666;
  transition: color 0.3s;
}

.collapse-btn:hover {
  color: #409eff;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #666;
}

.tags-view {
  height: 34px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.tags-view-wrapper {
  padding: 4px 16px;
  height: 100%;
  white-space: nowrap;
}

.tags-view-item {
  display: inline-flex;
  align-items: center;
  margin-right: 4px;
  padding: 0 8px;
  height: 26px;
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 3px;
  font-size: 12px;
  color: #666;
  text-decoration: none;
  transition: all 0.3s;
}

.tags-view-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
  border-color: #409eff;
}

.tags-view-item.active {
  background-color: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

.tags-view-item .close-btn {
  margin-left: 4px;
  width: 16px;
  height: 16px;
  vertical-align: middle;
  border-radius: 50%;
  text-align: center;
  transition: all .3s;
  transform-origin: 100% 50%;
}

.tags-view-item:not(.active) .close-btn:hover {
  background-color: #f56c6c;
  color: #fff;
}

.tags-view-item.active .close-btn:hover {
  background-color: #409eff;
  color: #fff;
}

.context-menu {
  position: fixed;
  z-index: 3000;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: #fff;
  border: 1px solid #e6e6e6;
}

.context-menu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}

.context-menu li:hover {
  background: #ecf5ff;
  color: #409eff;
}

.context-menu .el-icon {
  font-size: 14px;
}

.tags-view-container {
  display: flex;
  align-items: center;
  height: 100%;
}

.tags-view-item {
  transition: all 0.3s;
}

.tags-view-item.drag-over {
  border-color: #409eff;
  transform: scale(1.05);
  background-color: #ecf5ff;
}

.tags-view-item.first-tag {
  cursor: default;
}

.tags-view-item:not(.first-tag) {
  cursor: move;
}

/* 拖动时的样式 */
.tags-view-item:active {
  cursor: grabbing;
}

/* 主要内容区域 */
.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}
</style> 